<template>
    <Popup :show="showAction" position="bottom" :style="{ height: '85%' }">
        <div class="content">
            <div class="fe-title">
                <h3>选择城市</h3>
                <img src="@/assets/img/close-popup.png" alt="" @click="close" />
            </div>
            <div class="search-box">
                <Search v-model="cityNameValue" placeholder="请输入城市名称或拼音" @update:model-value="onSearchCity(cityNameValue)">
                    <template #left-icon>
                        <i class="iconfont icon-sousuo"></i>
                    </template>
                </Search>
            </div>
            <div class="city-box">
                <div v-if="!cityNameValue">
                    <div class="recently">
                        <div class="title">
                            当前城市
                        </div>
                        <div class="city-list">
                            <span @click="onSelectConfirm(locationCity)"><i class="iconfont icon-xuanzechengshi-dingwei"></i>{{ locationCity.name }}</span>
                            <span @click="getLocationCity">重新定位</span>
                        </div>
                        <template v-if="currentViewCityList.length">
                            <div class="title">
                                最近浏览
                            </div>
                            <div class="city-list">
                                <template v-for="(item,index) in currentViewCityList" :key="index">
                                    <span @click="onSelectConfirm(item)">{{ item.name }}</span>
                                </template>
                            </div>
                        </template>
                    </div>
                    <IndexBar :index-list="indexList">
                        <template v-for="(item,index) in cityList" :key="index">
                            <IndexAnchor :index="item.name" />
                            <Cell v-for="(city,i) in item.children" :key="i" :title="city.name" @click="onChangeCityName(city)">
                                <Icon v-if="currentCityId===city.id" name="success" color="#E60044" class="check-success" />
                            </Cell>
                        </template>
                    </IndexBar>
                </div>
                <div v-else>
                    <ul v-if="cityListAll.length" class="city-searchlist">
                        <li v-for="(item,index) in cityListAll" :key="index" @click="onChangeCityName(item)">
                            <span :class="currentCityId===item.id?'on':''" v-html="item.cityHtmlName"></span>
                            <Icon v-if="currentCityId===item.id" name="success" color="#E60044" />
                        </li>
                    </ul>
                    <Empty
                        v-else :image-size="[182, 125]"
                        image="https://puma-obs.xinchao.com/atprut/test/prut/2023/01/13/1673601926509.png" description="搜索无结果"
                    />
                </div>
            </div>
        </div>
    </Popup>
</template>

<script lang="ts" setup>
import { defineEmits, defineProps, reactive, ref, watch, onMounted} from 'vue';
import { Popup,Icon, IndexBar, IndexAnchor,Cell ,Search,Empty,Toast,NavBar } from 'vant';
import { store } from '@/store';
import {TreeChildModel,PositionModel} from './citySelecter.module';
import { getCityTreeData } from '@/api/common';

const emits = defineEmits(['confirm','close']);
const props = defineProps({
    showAction: {
        type: Boolean,
        default: false,
    },
});
const cityNameValue = ref('');
const cityListAll= ref<TreeChildModel[]>([]);
const cityList= ref<TreeChildModel[]>([]);
const citySearchList = ref<TreeChildModel[]>([]);
const currentCityId = ref('');
const currentViewCityList= ref<TreeChildModel[]>([]);
const locationCity = reactive({name: ''});
const indexList = ref<string[]>([])
const onSelectConfirm = (item:TreeChildModel)=>{
    if(item.id){
        emits('confirm',item);
    }else{
        const cityFilter = cityList.value.filter((city:TreeChildModel) => {
            return city.name === item.name;
        })[0];
        if(!!cityFilter){
            Object.assign(locationCity,cityFilter);
            emits('confirm',cityFilter);
        }else{
            Toast.fail('当前城市没有权限');
        }
    }

};

const getLocationCity = async() => {
    try {
        // eslint-disable-next-line
        const geolocation = await new BMap.Geolocation();
        // eslint-disable-next-line
        geolocation.getCurrentPosition(async (currentPositionData:PositionModel) => {
            const cityFilter = citySearchList.value.filter((city:TreeChildModel) => {
                return city.name === currentPositionData.address.city;
            })[0];

            if(!!cityFilter){
                Object.assign(locationCity,cityFilter);
            }else{
                locationCity.name = currentPositionData.address.city;
            }
        });

    } finally{

    }
};

onMounted(async()=>{
    cityList.value = await getCityTreeData(2) as unknown as TreeChildModel[];
    indexList.value =  cityList.value.map((item:TreeChildModel)=>item.name)
    const cityAllList = cityList.value.map((item:TreeChildModel)=>item.children);
    citySearchList.value = cityAllList.flat() as unknown as TreeChildModel[];
    await getLocationCity();
});
const onSearchCity = (name:string)=>{
    if(name){
        const filterName = citySearchList.value.filter((item:TreeChildModel)=>item.name.includes(name));
        cityListAll.value = filterName.map((item:TreeChildModel)=>{
            return {...item,cityHtmlName: item.name.replace(name,`<span style="color:#F7135E">${name}</span>`)};
        });
    }
};
const onChangeCityName = (item:TreeChildModel)=>{
    currentCityId.value = item.id;
    const index = currentViewCityList.value.findIndex((itemView:TreeChildModel)=>itemView.id===item.id);
    if(index===-1){
        store.commit('app/setViewCityList',item);
    }
    emits('confirm',item);

};
const close = ()=>{
    emits('close');
};

watch(() => props.showAction,(showAction) => {
    if(showAction){
        currentViewCityList.value = store.state.app.currentViewCityList as unknown as TreeChildModel[];
        cityNameValue.value ='';
        cityListAll.value = [];
    }
});
</script>

<style lang="scss" scoped>
::v-deep {
    [class~="van-sidebar-item--select::before"] {
        background-color: rgb(230 0 68 / 100%);
    }
    [class~="van-sidebar-item--select:active"] {
        color: rgb(230 0 68 / 100%);
    }
    [class~="--van-tree-select-item-active-color"] {
        color: rgb(230 0 68 / 100%);
    }
    [class~="van-index-bar__sidebar"] {
        top: 60%;
    }
    [class~="van-popup--bottom"] {
        border-radius: 0 !important;
    }
}
.recently {
    padding: 0 12px;
    margin-bottom: 24px;
    .title {
        font-weight: bold;
        font-size: 14px;
        color: #333333;
        margin-top: 24px;
    }
}

.city-list {
    margin-top: 12px;
    span {
        display: inline-block;
        width: 97px;
        height: 28px;
        background: #f8f8f8;
        border-radius: 4px;
        text-align: center;
        line-height: 28px;
        margin-right: 10px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
.content {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 100%;
    .city-searchlist {
        padding: 12px;
        li {
            padding: 16px 0;
            display: flex;
            justify-content: space-between;
        }
        span {
            &.on {
                color: #f7135e;
            }
        }
    }
}
.city-box {
    flex: 1;
    overflow: auto;
}
.check-success {
    padding-right: 10px;
}
.fe-title {
    display: flex;
    padding: 0 12px;
    margin-top: 20px;

    h3 {
        height: 22px;
        // font-family: PingFangSC-SNaNpxibold;
        font-weight: 600;
        font-size: 16px;
        color: #333333;
        text-align: center;
        flex: 1;
        margin-left: 20px;
    }

    img {
        width: 20px;
        height: 20px;
    }
}

</style>
